import { defineComponent, reactive, ref } from 'vue'
import { NSpace, NTag, NInput, useMessage } from 'naive-ui'
import type { InputInst } from 'naive-ui'
export default defineComponent({
  props: {
    modelValue: {
      type: Array,
      default: () => []
    },
    noRepeat: {
      type: Boolean,
      default: true
    }
  },
  emits: ['update:modelValue'],
  setup: function (props, { emit }) {
    const inputInstRef = ref<InputInst | null>(null)
    const toast = useMessage()
    const handClose = (index: number) => {
      const list = props.modelValue
      list.splice(index, 1)
      emit('update:modelValue', list)
    }
    const state = reactive({
      isEdit: false,
      keyword: ''
    })
    const handAdd = () => {
      state.isEdit = true
      state.keyword = ''
      setTimeout(() => {
        inputInstRef.value?.focus()
      }, 200)
    }
    const handBlur = () => {
      if (state.keyword) {
        const list = props.modelValue
        if (props.noRepeat) {
          const status = list.some((el: any) => el === state.keyword)
          if (status) {
            state.isEdit = false
            toast.error(`${state.keyword}已存在`)
            state.keyword = ''
            return
          }
        }
        list.push(state.keyword)
        emit('update:modelValue', list)
      }
      state.isEdit = false
      state.keyword = ''
    }

    const handleEnter = (event: any) => {
      if (event.key === 'Enter') {
        handBlur()
      }
    }
    return () => (
      <>
        <NSpace>
          {props.modelValue.map((el: any, index: number) => (
            <NTag closable onClose={() => handClose(index)}>
              {el}
            </NTag>
          ))}
          {state.isEdit ? (
            <NInput
              ref={inputInstRef}
              style={{ width: '80px' }}
              size="small"
              v-model:value={state.keyword}
              onBlur={handBlur}
              onKeydown={handleEnter}
            />
          ) : (
            <div onClick={handAdd}>
              <NTag>新增</NTag>
            </div>
          )}
        </NSpace>
      </>
    )
  }
})
